package com.cola.colaboot.utils;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cola.colaboot.config.exception.ColaException;
import com.cola.colaboot.module.system.pojo.SysDict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     *  文件上传
     * @param url   上传路径
     * @param fileName  文件名
     * @param multipartFile 上传文件
     */
    public static File saveFile(String url, String fileName, MultipartFile multipartFile) {
        if (!multipartFile.isEmpty()) {//判断文件是否为空
            try {
                long size = multipartFile.getSize();
                log.info("上传文件大小：" + (size / 1024) + "kb");
                File fileDir = new File(url);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                if (StringUtils.isBlank(fileName)){
                    String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
                    fileName = IdUtil.fastSimpleUUID()+suffix;
                }
                String filePath = fileDir.getAbsolutePath() + File.separator + fileName;
                File file = new File(filePath);
                multipartFile.transferTo(file);  //转存文件
                return file;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.toString());
                throw new RuntimeException("文件保存异常");
            }
        } else {
            throw new RuntimeException("文件为空");
        }
    }



    /**
     * 解压
     * @param zipFile 待解压文件
     * @param unzipFilePath 解压后的文件存储路径
     */
    public static void unzip(File zipFile,String unzipFilePath) throws Exception{
        ZipFile zfile = new ZipFile(zipFile.getAbsolutePath());
        Enumeration zList=zfile.entries();
        ZipEntry ze=null;
        byte[] buf=new byte[1024];
        while(zList.hasMoreElements()){
            ze=(ZipEntry)zList.nextElement();
            if(ze.isDirectory()){
                File f=new File(unzipFilePath+ze.getName());
                f.mkdir();
                continue;
            }
            File realFileName = getRealFileName(unzipFilePath, ze.getName());
            OutputStream os=new BufferedOutputStream(new FileOutputStream(realFileName));
            InputStream is=new BufferedInputStream(zfile.getInputStream(ze));
            int readLen=0;
            while ((readLen=is.read(buf, 0, 1024))!=-1) {
                os.write(buf, 0, readLen);
            }
            is.close();
            os.close();
        }
        zfile.close();
    }

    /**
     *  给定根目录，返回一个相对路径所对应的实际文件名.
    * @param baseDir 指定根目录
    * @param absFileName 相对路径名，来自于ZipEntry中的name
    * @return java.io.File 实际的文件
    */
    public static File getRealFileName(String baseDir, String absFileName){
        String[] dirs=absFileName.split("/");
        File ret=new File(baseDir);
        if(dirs.length>1){
            for (int i = 0; i < dirs.length-1;i++) {
                ret=new File(ret, dirs[i]);
            }
            if(!ret.exists())
                ret.mkdirs();
            ret=new File(ret, dirs[dirs.length-1]);
            return ret;
        }else{
            ret = new File(baseDir+absFileName);
        }
        return ret;
    }



    /***
     * 文件下载
     * @param file 需要下载文件
     */
    public static void download(File file, String contentType,boolean isOpen, HttpServletResponse res) throws IOException {
        InputStream inputStream = null;
        OutputStream os = null;
        try{
            String name = file.getName();
            inputStream = new FileInputStream(file);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len =0;
            while((len=inputStream.read(buffer))!=-1){
                outStream.write(buffer,0,len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            res.reset();
            if(isOpen){
                res.addHeader("Content-Disposition","inline;filename="+ URLEncoder.encode(name, StandardCharsets.UTF_8));
            }else {
                res.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name, StandardCharsets.UTF_8));
            }
            res.setContentType(contentType);//"image/jpeg","application/x-download"
            os = res.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
            throw new ColaException("下载失败");
        }finally {
            if(inputStream!=null){
                inputStream.close();
            }
            if(os!=null){
                os.close();
            }
        }
    }

}